/**
 * Created by Gordon on 2016/11/17.
 */
;
/**GMap
 */
function GMap() {
    var arr = {};
    this.put = function (key, value) {
        arr[key] = value;
    };
    this.get = function (key) {
        return arr[key] ? arr[key] : null;
    };
    this.remove = function (key) {
        delete arr[key]
    };
    this.eachMap = function (fn) {
        for (var key in arr) {
            fn(key, arr[key])
        }
    }
}

(function (window, $) {
    /**
     * Ajax setting
     */
    $.ajaxSetup({
        timeout: 30000,
        contentType: 'application/json',
        dataType: 'json',
        headers: {
            'Accept': 'application/json; charset=utf-8',
            'Content-Type': 'application/json'
        },
        error: function (xhr, status, e) {
            alert('加载失败!');
        },
        beforeSend: function (xhr) {
        },
        complete: function (xhr) {

        }
    });
    window.RESPONSE_STATE = {
        success: 0,
        failure: -1,
        timeout: -2,
        lostCode: -4
    };
    window.Dracula = {
        hideLoading: function () {
            setTimeout(function () {
            }, 0);
        },
        get: function (api, data, successCallback) {
            $.ajax({
                type: 'GET',
                url: api,
                data: data,
                success: function (resJson) {
                    if (typeof(successCallback) == 'function' && resJson) {
                        successCallback(resJson);
                    }
                },
                error: function (xhr) {
                },
                complete: function (xhr) {
                }
            });

        },
        post: function (api, data, successCallback) {
            $.ajax({
                type: 'POST',
                url: api,
                data: JSON.stringify(data),
                success: function (resJson) {
                    if (typeof(successCallback) == 'function' && resJson) {
                        successCallback(resJson);
                    }
                },
                error: function (xhr) {

                },
                complete: function (xhr) {
                }
            });
        },
        alert: function (msg, callback) {
            var topWin = window.parent ? window.parent : window;
            var index = topWin.layer.alert(msg, {}, function () {
                if (typeof(callback) == 'function') {
                    callback();
                }
                topWin.layer.close(index);
            });
        },
        tip: function (selector, content) {
            layer.tips(content, selector, {
                tips: [1, '#3595CC'],
                time: 4000
            });
        },
        confirm: function (content, yes, no) {
            var topWin = window.parent ? window.parent : window;
            var layIndex = topWin.layer.confirm(content, {
                btn: ['确定', '取消']
            }, function () {
                if (typeof(yes) == 'function') {
                    topWin.layer.close(layIndex);
                    yes();
                }
            }, function () {
                if (typeof(no) == 'function') {
                    no();
                } else {
                    topWin.layer.close(layIndex);
                }
            });
        },
        warning: function (content, callBack) {

        },
        success: function (content, callBack) {

        },
        message: function (content) {
            var topWin = window.parent ? window.parent : window;
            topWin.layer.open({
                type: 1,
                title: '消息',
                shade: 0,
                area: ['340px', '215px'],
                offset: 'rb',
                time: 10000,
                anim: 2,
                content: content
            });
        },
        error: function (content, callBack) {

        },
        openFrame: function (title, url) {
            var curWinName = window.name;
            url += url.indexOf('?') > 0 ? '&pWindow=' + curWinName : '?' + 'pWindow=' + curWinName;
            var topWin = window.parent ? window.parent : window;
            topWin.parent.layer.open({
                type: 2,
                title: title,
                shadeClose: false,
                shade: 0,
                maxmin: true,
                area: ['800px', '560px'],
                content: url
            });
        },
        closeFrame: function (window, refreshParentWindow) {
            var topWin = window.parent ? window.parent : window;
            if (topWin.layer) {
                topWin.layer.close(topWin.layer.getFrameIndex(window.name))
            }
            if (refreshParentWindow != undefined && refreshParentWindow) {
                var pWindow = Dracula.util.getQuery()['pWindow'];
                if (pWindow) {
                    $('.J_iframe', topWin.document).each(function (index, jframe) {
                        var jframeDoc = jframe.contentWindow.document;
                        var searchBtn = $('.i-btn-search', jframe.contentWindow.document);
                        if (searchBtn && searchBtn.length > 0) {
                            $(searchBtn[0]).click();
                        } else {
                            jframeDoc.location.reload(true);
                        }
                    });
                } else {
                    topWin.location.reload();
                }
            }
        },
        util: {
            isEmpty: function (input) {
                if (input == undefined || $.trim(input) === '') {
                    return true;
                }
                return false;
            },
            regex: {
                isZip: function (input) {
                    var re = /^[1-9][0-9]{5}$/;
                    return re.test(input);
                },
                isMobile: function (input) {
                    var mobileReg = /^1\d{10}$/;
                    return mobileReg.test(input);
                },
                isEmail: function (email) {
                    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                    return re.test(email);
                }
            },
            backToTop: function () {
                var left = 0;
                var $body = $('body');
                $backTop = $('.back-top');
                if ($body.width() <= 1280) { //普通Mac13寸笔记本,电脑笔记本,iPad等尺寸更小的设备
                    $backTop.addClass('fix-back-top');
                    $backTop.css({'right': '20px'});
                } else { // PC
                    var warp = $("body>.warp");
                    left = warp.offset().left + warp.width() + 8;
                    $backTop.css({'left': left + 'px'});
                }
                $backTop.css('bottom', '150px');
            },
            formatFullDateToZH: function (millisecond) {
                var date = new Date(millisecond);
                var month = date.getMonth() + 1;
                month = Dracula.util.fillLeftOneZeroWhenLess(month, 10);
                var thatDate = date.getDate();
                thatDate = Dracula.util.fillLeftOneZeroWhenLess(thatDate, 10);
                return date.getFullYear() + '年' + month + '月' + thatDate + '日';
            },
            formatFullDate: function (millisecond) {
                var date = new Date(millisecond);
                var month = date.getMonth() + 1;
                month = Dracula.util.fillLeftOneZeroWhenLess(month, 10);
                var thatDate = date.getDate();
                thatDate = Dracula.util.fillLeftOneZeroWhenLess(thatDate, 10);
                var hour = date.getHours();
                hour = Dracula.util.fillLeftOneZeroWhenLess(hour, 10);
                var mins = date.getMinutes();
                mins = Dracula.util.fillLeftOneZeroWhenLess(mins, 10);
                return date.getFullYear() + '/' + month + '/' + thatDate + ' ' + hour + ':' + mins;
            },
            formatTime: function (millisecond) {
                var date = new Date(millisecond);
                var hour = date.getHours();
                hour = Dracula.util.fillLeftOneZeroWhenLess(hour, 10);
                var mins = date.getMinutes();
                mins = Dracula.util.fillLeftOneZeroWhenLess(mins, 10);
                return hour + ':' + mins;
            },
            fillLeftOneZeroWhenLess: function (input, num) {
                if (parseInt(input) < num) {
                    return '0' + input;
                } else {
                    return input;
                }
            },
            loadCSS: function (url) {
                $('head').prepend('<link rel="stylesheet" href="' + url + '"/>');
            },
            checkBrowser: function () {
                if (/MicroMessenger/i.test(navigator.userAgent)) {
                    return 'wechat';
                } else if (/android/i.test(navigator.userAgent)) {
                    return 'android';
                } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                    return 'iOS';
                } else if (/Linux/i.test(navigator.userAgent)) {
                    return 'linux broswer';
                } else if (/Linux/i.test(navigator.platform)) {
                    return 'linux platform';
                } else if (/BlackBerry/i.test(navigator.userAgent)) {
                    return 'BlackBerry';
                } else {
                    return 'pc';
                }
            },
            isLowIE: function () {
                var isLowIE = false;
                if (navigator.DraculaName == "Microsoft Internet Explorer" && navigator.DraculaVersion.match(/7./i) == "7.") {
                    isLowIE = true;
                } else if (navigator.DraculaName == "Microsoft Internet Explorer" && navigator.DraculaVersion.match(/8./i) == "8.") {
                    isLowIE = true;
                } else if (navigator.DraculaName == "Microsoft Internet Explorer" && navigator.DraculaVersion.match(/9./i) == "9.") {
                    isLowIE = true;
                } else if (navigator.DraculaName == "Microsoft Internet Explorer") {
                    isLowIE = true;
                }
                return isLowIE;
            },
            setCookie: function (cname, cvalue, exdays) {
                var date = new Date();
                date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000));
                var expires = "expires=" + date.toUTCString();
                document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";
            },
            getQuery: function () {
                var url = location.search;
                var theRequest = {};
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    var strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            },
            StringStartWith: function (origin, contained) {
                if (origin == null || origin == "" || origin.length == 0 || contained.length > origin.length) {
                    return false;
                }
                return origin.substr(0, contained.length) == contained;
            },
            ellipsisStr: function (original, length) {
                if (original && original.length > length) {
                    return original.substring(0, length) + '...';
                }
                return '';
            },
            clearCookie: function () {
                var cookies = document.cookie.split(";");
                for (var i = 0; i < cookies.length; i++) {
                    var spcook = cookies[i].split("=");
                    deleteCookie(spcook[0]);
                }
                function deleteCookie(cookiename) {
                    var d = new Date();
                    d.setDate(d.getDate() - 1);
                    var expires = ";expires=" + d;
                    var name = cookiename;
                    //alert(name);
                    var value = "";
                    document.cookie = name + "=" + value + expires + "; path=/acc/html";
                }
            },
            deepCopy: function (obj) {
                var attr, newObj = {};
                if (typeof obj != 'object') return obj;
                for (attr in obj) {
                    newObj[attr] = Dracula.util.deepCopy(obj[attr]);
                }
                return newObj;
            },
            exportExcel: function (formQuery) {
                var $exportFrame = $('#exportFrame', window.parent.document);
                var $frameBody = $exportFrame.contents().find("body");
                $frameBody.empty().append('<form id="exportForm" action="admin/export" method="post" enctype="application/x-www-form-urlencoded"><input type="hidden" name="query" value="' + encodeURI(JSON.stringify(formQuery)) + '"></form>');
                $frameBody.find('#exportForm').submit();
            }
        }
    };
    /**
     * jQuery Extend
     */
})(window, jQuery);

//格式化时间
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
/*
 * 值的格式化。
 * */
var Format = {
    formatDateTime: function formatDateTime(val, row) {
        var now = new Date(val);
        return now.format("yyyy-MM-dd");
    },
    formatStatus: function formatStatus(val, row) {
        if (val == 1) {
            return '在职';
        } else {
            return '离职';
        }
    },
    formatSex: function formatSex(val, row) {
        if (val == 1) {
            return '男';
        } else {
            return '女';
        }
    },
    /**审核状态*/
    formatAuditStatu: function formatStatus(val, row) {
        if (val == 1) {
            return '通过';
        } else {
            return '未通过';
        }
    },
    /*审核是否*/
    formatIsOk: function formatIsOk(val, row) {
        if (val == 1) {
            return "是"
        } else {
            return "否"
        }
    }
};
/**
 * 表单参数序列化
 */
(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        $(this.serializeArray()).each(function () {
            serializeObj[this.name] = this.value;
        });
        return serializeObj;
    };
})(jQuery);

/**
 * 模态弹窗
 * options:{
 * title:标题,
 * url:嵌入页面路径
 * content:内容块，仅在url为空时有效，内容为html元素
 * onConfirm:
 * onCancel:
 * }
 */
(function ($) {
    $.fn.showModalWin = function (options) {
        window.top.layer.open("modal")

    };
})(jQuery);

function getMaxRowCount() {
    var e = window,
        a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    var tableHeight = e[a + 'Height'] - $(".searchform").outerHeight(true) - 54 - 59;
    var rows = Number((tableHeight / 32).toFixed(0)) - 3;
    if (rows < 10) {
        rows = 10;
    }
    return rows;
}
//进行Iframe的自动撑开,让所有父页面的Iframe都自动适应包含页高度
function autoHeight() {
    var doc = document,
        p = window;
    while (p = p.parent) {
        var frames = p.frames,
            frame,
            i = 0;
        while (frame = frames[i++]) {
            if (frame.document == doc) {
                frame.frameElement.style.height = doc.body.scrollHeight + 'px'; // 这里一定要注意 火狐必须要加'px‘ 否则火狐无效
                doc = p.document;
                break;
            }
        }
        if (p == top) {
            break;
        }
    }
}